from rest_framework import serializers
from django.core.validators import FileExtensionValidator #文件后缀名验证器
#get_available_image_extensions 可用图片文件拓展名

class UploadImageSerializer(serializers.Serializer ):
    #ImageField校验上次文件是否为图片
    image = serializers.ImageField(
        validators=[FileExtensionValidator(['png','jpg','jpeg','gif'])],
        error_messages={'required':'请上传图片！','invalid_image':'请上传正确格式的图片！'}
    )

    def validate_image(self, value):
        #图片大小单位是字节 1024B->1KB  1024kB->1MB
        max_size = 0.5 * 1024 * 1024
        size = value.size
        if size > max_size:
            raise serializers.ValidationError('图片最大不能超过0.5MB!')
        return value

